<template>
  <div class="record-page">
    <el-card>
      <div class="user-info-row">
        <div class="user-info-item">
          <span class="label">账号：</span>
          <span class="value">{{userInfo.userAccount}}</span>
        </div>
        <div class="user-info-item">
          <span class="label">余额：</span>
          <span class="value">
            <span class="number">{{userInfo.balance}}</span>
            <span>元</span>
          </span>
        </div>
        <div class="user-info-item">
          <span class="label">状态：</span>
          <span class="value">
            <span class="success-text" v-if="userInfo.status === 200">正常</span>
            <span class="error-text" v-if="userInfo.status === 403">已锁定</span>
          </span>
        </div>
        <div class="user-info-item">
          <span class="label">API文档：</span>
          <span class="value">
            <el-button type="primary" link @click="handleViewApiDoc">查看</el-button>
          </span>
        </div>
<!--        <div class="user-info-item">-->
<!--          <span class="label">userId：</span>-->
<!--          <span class="value">{{userInfo.userId}}</span>-->
<!--        </div>-->
<!--        <div class="user-info-item">-->
<!--          <span class="label">API Token：</span>-->
<!--          <span class="value">-->
<!--            <el-button type="primary" link @click="handleViewApiToken">查看</el-button>-->
<!--          </span>-->
<!--        </div>-->
      </div>
    </el-card>
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">API调用记录</span>
          <div class="conditions">
            <span>模型：</span>
            <el-select v-model="conditionState.model" placeholder="请选择" style="width: 200px" clearable>
              <el-option-group
                  v-for="group in modelList"
                  :key="group.platform"
                  :label="group.name">
                <el-option
                    v-for="item in group.list"
                    :key="group.platform +'[#]'+item.code"
                    :label="group.name + '：' +item.label"
                    :value="group.platform +'[#]'+item.code"/>
              </el-option-group>
            </el-select>
            <span>日期范围：</span>
            <el-date-picker
                v-model="conditionState.dateRange"
                type="daterange"
                unlink-panels
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts"/>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>
        </div>
      </template>
      <div id="token_charts" :style="{ width: '100%', height: '340px' }"></div>
      <div id="price_charts" :style="{ width: '100%', height: '340px' }"></div>
      <el-table :data="recordList" style="width: 100%">
        <el-table-column prop="userAccount" label="账号" width="180" >
          <template #default="scope">
            <span>{{scope.row.userInfo ? scope.row.userInfo.userAccount : ''}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="日期" width="160"/>
        <el-table-column prop="inToken" label="[输入|输出|总计]Tokens" >
          <template #default="scope">
            <span>{{scope.row.inToken}}</span>
            <el-divider direction="vertical" />
            <span>{{scope.row.outToken}}</span>
            <el-divider direction="vertical" />
            <span>{{scope.row.totalToken}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inToken" label="[输入|输出|总计]费用" >
          <template #default="scope">
            <span>{{scope.row.inPrice}}</span>
            <el-divider direction="vertical" />
            <span>{{scope.row.outPrice}}</span>
            <el-divider direction="vertical" />
            <span>{{scope.row.totalPrice}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="model" label="模型"  width="200">
          <template #default="scope">
            <span v-if="modelObj[scope.row.model]">{{modelObj[scope.row.model]}}</span>
            <span v-else>{{scope.row.model}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
        v-model="docModalVisible"
        title="API文档说明"
        width="60%">
      <div class="doc-row">
        <div class="label">userId</div>
        <div class="value">{{userInfo.userId}}</div>
      </div>
      <div class="doc-row">
        <div class="label">API Token</div>
        <div class="value">
          <el-button type="primary" link @click="handleViewApiToken">查看</el-button>
        </div>
      </div>
      <div class="doc-content">
        <el-tabs v-model="apiTabActive">
          <el-tab-pane label="百度" name="baidu">
            <div class="doc-row">
              <span class="label">API 地址</span>
              <span class="value">{{docDomain}}/ai-repost/stream/baidu/chat</span>
            </div>
            <div class="doc-row">
              <span class="label">Method</span>
              <span class="value">POST 流式响应</span>
            </div>
            <div class="doc-row">
              <span class="label">Headers参数</span>
              <span class="value">api-token</span>
            </div>
            <div class="doc-row">
              <span class="label">Body参数</span>
              <div class="value">
                <div class="table">
                  <div class="tr header">
                    <span class="td">参数名称</span>
                    <span class="td">参数类型</span>
                    <span class="td">是否必传</span>
                    <span class="td desc-td">参数说明</span>
                  </div>
                  <div class="tr">
                    <span class="td">userId</span>
                    <span class="td">String</span>
                    <span class="td">是</span>
                    <span class="td desc-td">用户身份唯一标识</span>
                  </div>
                  <div class="tr">
                    <span class="td">content</span>
                    <span class="td">String</span>
                    <span class="td">是</span>
                    <span class="td desc-td">问题描述</span>
                  </div>
                  <div class="tr">
                    <span class="td">model</span>
                    <span class="td">String</span>
                    <span class="td">是</span>
                    <span class="td desc-td">使用的模型，不传默认值为dsr1，即DeepSeek-R1模型</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="doc-row">
              <span class="label">model取值</span>
              <div class="value">
                <p>1. DeepSeek-V3，model参数值为：dsv3</p>
                <p>2. DeepSeek-R1，model参数值为：dsr1</p>
              </div>
            </div>
            <div class="doc-row">
              <span class="label">接口返回</span>
              <div class="value">
                <p>接口调用成功会以流式数据返回message对象字符串，message格式如下</p>
                <img src="../../assets/images/message_desc.png"/>
                <img src="../../assets/images/chat1.png"/>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="火山" name="volces">
            <div class="doc-row">
              <span class="label">API 地址</span>
              <span class="value">{{docDomain}}/ai-repost/stream/volces/chat</span>
            </div>
            <div class="doc-row">
              <span class="label">Method</span>
              <span class="value">POST 流式响应</span>
            </div>
            <div class="doc-row">
              <span class="label">Headers参数</span>
              <span class="value">api-token</span>
            </div>
            <div class="doc-row">
              <span class="label">Body参数</span>
              <div class="value">
                <div class="table">
                  <div class="tr header">
                    <span class="td">参数名称</span>
                    <span class="td">参数类型</span>
                    <span class="td">是否必传</span>
                    <span class="td desc-td">参数说明</span>
                  </div>
                  <div class="tr">
                    <span class="td">userId</span>
                    <span class="td">String</span>
                    <span class="td">是</span>
                    <span class="td desc-td">用户身份唯一标识</span>
                  </div>
                  <div class="tr">
                    <span class="td">content</span>
                    <span class="td">String</span>
                    <span class="td">是</span>
                    <span class="td desc-td">问题描述</span>
                  </div>
                  <div class="tr">
                    <span class="td">model</span>
                    <span class="td">String</span>
                    <span class="td">是</span>
                    <span class="td desc-td">使用的模型，不传默认值为dsr1，即DeepSeek-R1模型</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="doc-row">
              <span class="label">model取值</span>
              <div class="value">
                <p>1. DeepSeek-V3，model参数值为：dsv3</p>
                <p>2. DeepSeek-R1，model参数值为：dsr1</p>
              </div>
            </div>
            <div class="doc-row">
              <span class="label">接口返回</span>
              <div class="value">
                <p>接口调用成功会以流式数据返回message对象字符串，message格式如下</p>
                <img src="../../assets/images/message_desc.png"/>
                <img src="../../assets/images/chat1.png"/>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, nextTick, onMounted, onUnmounted} from 'vue'
import api from '../../api/index.js'
import * as echarts from "echarts";
import constants from "~/common/constants.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {ArrowDown} from "@element-plus/icons-vue";
import {md5} from 'js-md5'
import Decimal from "decimal.js";
import common from "~/common/common.js";
import {formatTimeToDateStr} from "~/common/utils.js";

const user = common.getLocalUser()
const userInfo = ref({})
const docModalVisible = ref(false)
const docDomain = 'http://115.190.9.96'
const apiTabActive = ref('baidu')
const conditionState = ref({
  userId: user.userId,
  startDate: '',
  endDate: '',
  model: '',
  dateRange: ['', '']
})
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [formatTimeToDateStr(start.getTime()), formatTimeToDateStr(end.getTime())]
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [formatTimeToDateStr(start.getTime()), formatTimeToDateStr(end.getTime())]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [formatTimeToDateStr(start.getTime()), formatTimeToDateStr(end.getTime())]
    },
  },
]
conditionState.value.dateRange = shortcuts[0].value()


const recordList = ref([])
const modelList = ref([])
const modelObj = ref({})


const getAllModelList = () => {
  modelList.value = []
  api.getModelList().then((res) => {
    if (res.data) {
      res.data.forEach((item) => {
        const k = item.platform
        const platform = item.name
        item.list.forEach((model) => {
          modelObj.value[`${k}[#]${model.code}`] = `${platform}：${model.label}`
        })
      })
      modelList.value = res.data
    }
  })
}
const getUserInfo = () => {
  api.getUserInfo(user.userId).then((res) => {
    if (res.code === 0) {
      userInfo.value = res.data
    }
  })
}
const handleViewApiToken = () => {
  api.getApiToken({userId: user.userId}).then((res) => {
    if (res.data && res.data.token) {
      ElMessageBox.alert(`<span class="token-text">${res.data.token}</span>`, `API调用Token，请误泄露!!!`, {
        confirmButtonText: '确定',
        'button-size': 'small',
        dangerouslyUseHTMLString: true,
        callback: () => {}
      })
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  }).catch((e) => {
    ElMessage.error('查询异常')
  })
}
const handleViewApiDoc = () => {
  docModalVisible.value = true
}
const getRecordList = async () => {
  if (!conditionState.value.userId) {
    ElMessage.error('请选择要查询的用户')
    return
  }
  recordList.value = []
  const params = {
    startDate: '',
    endDate: '',
    userId: conditionState.value.userId,
    model: conditionState.value.model
  }
  if (conditionState.value.dateRange) {
    if (conditionState.value.dateRange[0]) {
      params.startDate = conditionState.value.dateRange[0]
    }
    if (conditionState.value.dateRange[1]) {
      params.endDate = conditionState.value.dateRange[1]
    }
  }
  let xData = []
  let tokenSeriesData = [
    {
      name: '输入Tokens',
      type: 'line',
      color: '#0674f5',
      data: []
    },
    {
      name: '输出Tokens',
      type: 'line',
      color: '#33c533',
      data: []
    },
    {
      name: '总Tokens',
      type: 'line',
      color: '#d22008',
      data: []
    },
  ]
  let priceSeriesData = [
    {
      name: '输入花费',
      type: 'line',
      color: '#0674f5',
      data: []
    },
    {
      name: '输出花费',
      type: 'line',
      color: '#33c533',
      data: []
    },
    {
      name: '总花费',
      type: 'line',
      color: '#d22008',
      data: []
    },
  ]
  try {
    const res = await api.getRecordList(params)
    if (res.data) {
      let currentDate = ''
      const dataArr = []
      res.data.forEach((item) => {
        item.totalPrice = new Decimal(item.inPrice).plus(item.outPrice).valueOf()
        if (currentDate !== item.date) {
          currentDate = item.date
          dataArr.push({...item})
        } else {
          const dataObj = dataArr[dataArr.length - 1]
          dataObj.inToken = Number(dataObj.inToken) + Number(item.inToken)
          dataObj.outToken = Number(dataObj.outToken) + Number(item.outToken)
          dataObj.totalToken = Number(dataObj.totalToken) + Number(item.totalToken)
          dataObj.inPrice = new Decimal(item.inPrice).plus(dataObj.inPrice).valueOf()
          dataObj.outPrice = new Decimal(item.outPrice).plus(dataObj.outPrice).valueOf()
          dataObj.totalPrice = new Decimal(dataObj.inPrice).plus(dataObj.outPrice).valueOf()
        }
      })
      dataArr.forEach((item) => {
        xData.push(item.date)
        tokenSeriesData[0].data.push(item.inToken)
        tokenSeriesData[1].data.push(item.outToken)
        tokenSeriesData[2].data.push(item.totalToken)
        priceSeriesData[0].data.push(item.inPrice)
        priceSeriesData[1].data.push(item.outPrice)
        priceSeriesData[2].data.push(item.totalPrice)
      })
      recordList.value = res.data
    }
  } catch(e){
    console.log(e)
  }
  initTokensCharts(xData, tokenSeriesData)
  initPriceCharts(xData, priceSeriesData)
}
const handleSearch = () => {
  conditionState.value.pageIndex = 1
  getRecordList()
}

let tokensCharts = null;
let priceCharts = null;

const initTokensCharts = (xData, seriesData) => {
  if (!tokensCharts) {
    tokensCharts = echarts.init(document.getElementById("token_charts"));
  }
  tokensCharts.setOption({
    title: {
      text: "tokens用量",
    },
    legend: {
      data: ['输入Tokens', '输出Tokens', '总Tokens']
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData
    },
    yAxis: {
      type: 'value'
    },
    series: seriesData,
  });
}
const initPriceCharts = (xData, seriesData) => {
  if (!priceCharts) {
    priceCharts = echarts.init(document.getElementById("price_charts"));
  }
  priceCharts.setOption({
    title: {
      text: "费用(元)",
    },
    legend: {
      data: ['输入花费', '输出花费', '总花费']
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function (value) {
          return value.toFixed(6); // 保留6位小数
        }
      }
    },
    series: seriesData,
  });
}

window.onresize = function () {
  tokensCharts.resize();
  priceCharts.resize();
}
getAllModelList()
getUserInfo()
onMounted(() => {
  getRecordList()
});
onUnmounted(() => {
  if (tokensCharts) {
    tokensCharts.dispose();
  }
  if (priceCharts) {
    priceCharts.dispose();
  }
});
</script>

<style scoped lang="scss">
.el-card{
  margin-top: 20px;
}
.pagination-box{
  position: relative;
  padding: 0.5rem 0;
  display: flex;
  justify-content: flex-end;
}
.user-info-row{
  position: relative;
  display: flex;
  align-items: center;
}
.user-info-item{
  position: relative;
  display: flex;
  align-items: flex-end;
  height: 2rem;
  .label{
    color: var(--el-text-color-disabled);
    min-width: 50px;
  }
  .value{
    color: var(--el-text-color-primary);
  }
  .number{
    color: var(--el-color-primary);
    font-weight: bold;
    font-size: 2rem;
    line-height: 2rem;
    margin-right: 3px;
  }
  &+.user-info-item{
    margin-left: 20px;
  }
}
.doc-row{
  display: flex;
  position: relative;
  padding: 8px 0;
  .label{
    font-weight: bold;
    width: 160px;
    min-width: 160px;
  }
  .value{
    flex: 1;
    color: rgba(0,0,0,0.6);
    img{
      max-width: 100%;
    }
  }
  p+p{
    margin-top: 8px;
  }
}
.doc-content{
  margin-top: 20px;
  position: relative;

  .table{
    position: relative;
    .tr{
      position: relative;
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid rgba(0,0,0,0.1);
      .td{
        width: 20%;
        min-width: 20%;
        text-align: left;
      }

      .desc-td{
        width: 40%;
        min-width: 40%;
      }
    }
    .header{
      font-weight: bold;
      padding-top: 0;
    }
  }

}
</style>
